﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

#if false
using alib.Classification.Maxent;
#endif
using agree.mrs;

namespace agree
{
	public class theModel
	{
#if false
		IClassifier m_cls;
#endif

		public theModel()
		{
#if false
			m_cls = ClassifierUtilities.ReadClassifier("experiments\\mrsranking\\mrs.me");
#endif
		}

		public double Score(HashSet<String> feats)
		{
#if false
			//RuntimeEvent re = new RuntimeEvent((ICollection)(feats.Where(f => m_cls.FeatureVoc.Contains(f)).Select(f => m_cls.FeatureVoc.IndexOf(f))).ToArray());
			var use_feats = feats.Where(f => m_cls.FeatureVoc.Contains(f)).ToArray();
			RuntimeEvent re = new RuntimeEvent(use_feats);
			var classif = m_cls.Classify(re);
			return classif.First(c => c.Value == "1").Weight;
#else
			return double.NaN;
#endif
		}
	}

	public class MrsRanking
	{
		private static theModel model = null;
		public static theModel Model
		{
			get
			{
				if (model == null)
					model = new theModel();
				return model;
			}
		}

		public static double ScoreMrs(Mrs mrs)
		{
			HashSet<String> feats = new HashSet<String>();
			ExtractFeatures(feats, mrs);
			return Model.Score(feats);
		}

		public static void ExtractFeatures(HashSet<String> feats, Mrs mrs)
		{
			DependencyMrs dmrs = new DependencyMrs(mrs);

			feats.Add("Bias");

			foreach (var pred in dmrs.preds)
			{
				feats.Add(String.Format("Pred:{0}", pred));
			}

			for (int i = 0; i < dmrs.preds.Length; i++)
			{
				foreach (var link in dmrs.links[i])
				{
					if (link.link_type != DependencyMrs.DMRSLinkType.NONE && link.to != -1)
					{
						String from_pred = dmrs.preds[link.from];
						String to_pred = dmrs.preds[link.to];

						feats.Add(String.Format("Link:{0},{1},{2}", from_pred, link.idx_arg, to_pred));
						feats.Add(String.Format("LinkTo:{0},{1}", to_pred, link.idx_arg));
						feats.Add(String.Format("LinkFrom:{0},{1}", from_pred, link.idx_arg));

						if (link.link_type == DependencyMrs.DMRSLinkType.QEQ)
						{
							feats.Add(String.Format("QEQ:{0},{1},{2}", from_pred, link.idx_arg, to_pred));
							feats.Add(String.Format("QEQTo:{0},{1}", to_pred, link.idx_arg));
							feats.Add(String.Format("QEQFrom:{0},{1}", from_pred, link.idx_arg));
						}

						if (link.link_type == DependencyMrs.DMRSLinkType.EQ)
						{
							feats.Add(String.Format("SameLabel:{0},{1}", from_pred, to_pred));
						}
					}
				}
			}
		}
	};
}
